<template>
  <div id="login">
    <h1 class="titleBook">图 书 管 理 系 统</h1>
    <div class="login_box">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
      >
        <el-menu-item index="1">登录账号</el-menu-item>
        <el-menu-item index="2">注册账号</el-menu-item>
      </el-menu>
      <!-- 登录表单区域 -->
      <el-form
        v-show="menuIndex === '1'"
        ref="login_form_ref"
        :model="showLoginForm"
        :rules="login_form_rules"
        label-width="0px"
        class="login_form"
      >
        <!-- 账号 -->
        <el-form-item prop="username">
          <el-input
            v-model="showLoginForm.username"
            prefix-icon="iconfont icon-user"
            placeholder="用户名"
            v-focus
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="showLoginForm.password"
            type="password"
            prefix-icon="iconfont icon-password"
            placeholder="密码"
            show-password
            @keyup.enter.native="login(showLoginForm)"
          ></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="login(showLoginForm)"
            >登录</el-button
          >
          <!-- <el-button @click="create_user">去注册</el-button> -->
          <el-button @click="login_form_reset(login_form_ref)" type="info"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 注册新用户区域 -->
      <el-form
        v-show="menuIndex === '2'"
        ref="add_form_ref"
        :model="add_form"
        :rules="login_form_rules"
        label-width="0px"
        class="add_form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="add_form.username"
            prefix-icon="iconfont icon-user"
            placeholder="用户名"
            v-focus
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="add_form.password"
            type="password"
            prefix-icon="iconfont icon-password"
            placeholder="密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="add_form.passwordTrue"
            type="password"
            prefix-icon="iconfont icon-password"
            placeholder="确认密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="createUserBtn">
            立即注册
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog
      title="证明是本人操作 请进行验证"
      :visible.sync="verifyDialogVisible"
      width="350px"
    >
      <slide-verify
        :l="42"
        :r="10"
        :w="310"
        :h="155"
        slider-text="向右滑动"
        @success="onSuccess"
        @fail="onFail"
        @refresh="onRefresh"
      ></slide-verify>
      <div>{{ msg }}</div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
  inject: ["reload"],
  data() {
    return {
      // 表单验证规则对象
      login_form_rules: {
        // 验证用户名是否合法
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      // 判断是否进行注册
      isCreate: false,
      // 添加用户 表单
      add_form: {
        username: "",
        password: "",
        passwordTrue: "",
      },
      // 控制验证对话框 展示 隐藏
      verifyDialogVisible: false,
      // 验证返回的值
      msg: "",
      // 导航菜单默认选中
      activeIndex: "1",
      // 导航菜单 index
      menuIndex: "1",
    };
  },
  created() {
    // this.getUserInfo();
    // this.$store.dispatch("getUserList");
  },
  computed: {
    ...mapGetters(["showLoginForm"]),
  },
  methods: {
    // 点击重置按钮，重置表单
    login_form_reset() {
      // this.$refs.login_form_ref.resetFields();
      this.$store.commit("infoLoginForm", {});
    },
    // 点击登录
    async login() {
      this.$store.commit("infoLoginForm", this.showLoginForm);
      this.$refs.login_form_ref.validate((valid) => {
        if (valid) return (this.verifyDialogVisible = true);
        this.$message.info("请输入账号密码");
      });
    },
    // 行为式验证码验证成功后的处理函数
    async onSuccess(e) {
      let str = (e / 1000).toFixed(1);
      this.msg = `太棒了 只用了 ${str} 秒！`;
        // 登录校验
      if (this.menuIndex === "1") {
        let res = await this.$axios.post("/login", {
          user: this.showLoginForm,
        });
        this.showLoginForm.password = "";
        setTimeout(() => {
          this.reload();
          if (res.data.code === 200) {
            this.$message.success("登陆成功");
            // 获取登录的用户资料 保存到 vuex 中的 state 中
            this.$store.dispatch("getUsrInfo", this.showLoginForm.username);
            // 把登陆的用户名 放到 缓存中
            localStorage.setItem("loginUsername", this.showLoginForm.username);
            // 设置登录用户信息
            this.$store.commit("infoLoginUser", res.data.userInfo[0]);
            // 把登陆的用户信息放到缓存中 并存到缓存
            // stringify JSON 转换为 字符串
            let userJson = JSON.stringify(res.data.userInfo[0]);
            window.localStorage.setItem("loginUser", userJson);
            // 登录成功之后生成token 放到缓存
            window.localStorage.setItem("token", res.data.token);
            // 登陆成功 页面刷新 导航守卫重新执行 注：此时有 token 可以进入首页
            location.reload();
          } else {
            this.$message.error("账号或密码错误 请重新输入");
            this.verifyDialogVisible = false;
          }
        }, 500);
      } else {
        // 注册校验
        if (this.add_form.password === this.add_form.passwordTrue) {
          this.$refs.add_form_ref.validate(async (valid) => {
            if (!valid) return this.$message.info("不能为空");
            let res = await this.$axios.post("/user", {
              username: this.add_form.username,
              password: this.add_form.password,
            });
            // this.add_form = {};
            if (res.data.code === 200) {
              this.$message.success("注册成功");
              this.verifyDialogVisible = false;
              setTimeout(() => {
                location.reload();
              }, 1000);
            } else {
              this.verifyDialogVisible = false;
              this.menuIndex = "2";
              this.$message.error("注册失败，确保账号的唯一性");
              this.add_form = {};
            }
          });
        } else {
          this.verifyDialogVisible = false;
          // this.reload();
          this.menuIndex = "2";
          this.add_form.passwordTrue = "";
          this.$message.error("两次密码不一致！");
        }
      }
    },
    // 行为式验证码验证失败 后的处理函数
    onFail() {
      this.msg = "验证失败";
    },
    // 行为式验证码验证失败后重新刷新验证码的处理函数
    onRefresh() {
      this.msg = "";
    },
    // 点击注册 展示验证码
    createUserBtn() {
      this.menuIndex = "2";
      // this.verifyDialogVisible = true;
      this.$refs.add_form_ref.validate((valid) => {
        if (valid) return (this.verifyDialogVisible = true);
        this.$message.info("不能为空");
      });
    },
    // 点击导航菜单 触发
    handleSelect(key) {
      this.menuIndex = key;
    },
  },
  // 使用directives注册v-focus全局指令
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector("input").focus();
      },
    },
  },
};
</script>
<style lang="less" scoped>
#login {
  .titleBook {
    color: #fff;
    position: absolute;
    top: 27%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  height: 100%;
  height: 100vh;
  background-color: #2b4b6b;
  .login_box {
    width: 450px;
    height: 350px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    .login_admin_head {
      width: 130px;
      height: 130px;
      background-color: #fff;
      border: 1px solid #eee;
      border-radius: 50%;
      box-shadow: 0 0 10px #ddd;
      padding: 10px;
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: #eee;
      }
    }
    .btns {
      // float: right;
      display: flex; // 弹性盒模型
      justify-content: flex-end; // 尾部对齐
    }

    .login_form,
    .add_form {
      width: 100%;
      padding: 0 20px;
      box-sizing: border-box;
      position: absolute;
      bottom: 40px;
    }
    .add_form {
      bottom: 20px;
    }
  }
}
</style>